<template>
    <!-- 包括页头、检索框、页尾以及登录注册等基本功能 -->
    <a-layout style="min-height: 100vh">
        <a-layout :style="{
            backgroundImage: 'url(' + backGroundImg + ')',
            backgroundRepeat: 'no-repeat', backgroundSize: '1600px 200px'
        }" style="background-color: #fff;">
            <a-layout-header style="background: transparent; padding: 0; margin-bottom: 20px;">
                <div style="display: flex;">
                    <div>
                        <img src="@/assets/logo-no-background.png" style="height: 60px;" @click="$router.push('/homepage_demo' + '?randomId=' + Math.random())" />
                    </div>
                    <div v-if="!login" style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-button style="background: transparent; color: white" @click="onLoginShow">
                            <template #icon><user-outlined style="color: white"/></template>
                            登录
                        </a-button>
                    </div>
                    <div v-else style="margin-left: auto; margin-right: 10px; margin-top: 5px">
                        <a-dropdown>
                            <a-button style="background: transparent; color: white">
                                <user-outlined style="color: white"/>
                                {{ $store.state.username }}
                                <DownOutlined />
                            </a-button>
                            <template #overlay>
                                <a-menu @click="onMenuClick">
                                    <a-menu-item key="center">
                                        <span style="display: flex; justify-content: center;">个人中心</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="favorite">
                                        <span style="display: flex; justify-content: center;">我的收藏</span>
                                    </a-menu-item>
                                    <a-menu-item key="interest">
                                        <span style="display: flex; justify-content: center;">我的关注</span>
                                    </a-menu-item>
                                    <a-menu-divider />
                                    <a-menu-item key="logout">
                                        <span style="display: flex; justify-content: center;">退出登录</span>
                                    </a-menu-item>
                                </a-menu>
                            </template>
                        </a-dropdown>
                    </div>
                </div>
                <hr class="custom-divider" />
            </a-layout-header>
            <a-layout-content>
                <div style="margin-top: 30px; margin-left: 420px">
                    <a-select defaultValue="title" :options="searchOptions" v-model:value="searchField" size="large" style="width: 80px" />
                    <a-input v-model:value="searchQuery" placeholder="请输入检索词" size="large" style="width: 580px; margin-left: 10px" />
                    <a-button type="primary" size="large" style="width: 100px; margin-left: 10px" @click="onSearch">
                        <template #icon><SearchOutlined /></template>
                        检索
                    </a-button>
                    <span style="color: white; margin-left: 10px ;cursor: pointer" @click="$router.push('/advancedSearch_demo')">高级检索></span>
                </div>
                <div style="margin-left: 200px; margin-top: 80px; display: flex; align-items: center;">
                    <user-outlined style="font-size: 100px" />
                    <div v-if="author" style="margin-left: 30px">
                            <span style="color:#0B0E47; font-size: 20px">
                                {{ author.author_name }}
                            </span>
                        <a-button v-if="interest" :size="large" style="margin-left: 10px; background-color: transparent; border-radius: 30px;"  @click="handleInterest(author.author_id)">
                            <template #icon>
                                <heart-filled :style="{color: 'orangered'}" />
                            </template>
                            取消关注
                        </a-button>
                        <a-button v-else :size="large" style="margin-left: 10px; background-color: transparent; border-radius: 30px;"  @click="handleInterest(author.author_id)">
                            <template #icon>
                                <heart-outlined />
                            </template>
                            关注
                        </a-button>
                        <br/>
                        <span style="color:#6C6C6C; font-size: 16px">
                                UID:{{ author.author_id }}
                            </span>
                        <br/>
                        <span style="color:#0B0E47; font-size: 16px; font-weight: bold">
                                总发文量:{{ paperList.length }}&emsp;总被引量:{{ citationCountSum }}&emsp;h指数:{{ hIndex }}
                            </span>
                    </div>
                </div>
                <div style="margin-left: 200px; margin-top: 30px; display: flex; align-items: flex-start;">
                    <div style="border-right: 1px solid #0B0E47; width: 800px">
                        共发表 {{paperList.length}} 篇论文
                        <a-timeline>
                            <a-timeline-item v-for="item in paperList" :key="item.paper_id">
                            <span :style="{ marginRight: '10px', color: item.isTitleHovered ? '#1151D9' : '#0B0E47', textDecoration: item.isTitleHovered ? 'underline' : 'none' , fontSize: '16px', cursor: 'pointer'}"
                                  @mouseover="item.isTitleHovered = true"
                                  @mouseleave="item.isTitleHovered = false"
                                  @click="handleRead(item.paper_id)">
                                {{item.title}}
                            </span>
                                <a-tag v-for="tag in item.categories" color="blue">{{tag}}</a-tag>
                                <br/>
                                <span style="color: #6C6C6C; font-size: 12px">
                                <!-- 作者列表，可跳转至作者界面 -->
                                作者:
                                <template v-for=" (author, index) in item.authors"
                                          :key="author.author_id">
                                    <u :style="{ color: author.isHovered ? '#1151D9' : '#6C6C6C', textDecoration: author.isHovered ? 'underline' : 'none', cursor: 'pointer' }"
                                       @mouseover="author.isHovered = true"
                                       @mouseleave="author.isHovered = false"
                                       @click="handleAuthor(author.author_id)">
                                        {{ author.author_name }}
                                    </u>
                                    <span v-if="index < item.authors.length - 1">; </span>
                                </template>
                            </span>
                                <br/>
                                <span style="color: #6C6C6C; font-size: 12px">
                                发表时间:{{item.update_date}}
                            </span>
                                <span style="margin-left: 30px; color: #0B0E47; font-size: 12px; font-weight: bold">被引量:{{ item.citationCount }}</span>
                            </a-timeline-item>
                        </a-timeline>
                    </div>
                    <div style="margin-left: 20px; margin-right: 20px;">
                        <div>
                            <span style="font-size: 20px; color: #0B0E47">
                                作者合作网络
                            </span>
                            <div style="margin-top: 10px; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.5); border-radius: 10px;">
                                <div ref="chart" style="width: 500px; height: 300px;"></div>
                            </div>
                        </div>
                        <div style="margin-top: 30px">
                            <span style="font-size: 20px; color: #0B0E47">
                                研究兴趣云
                            </span>
                            <div style="margin-top: 10px; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.5); border-radius: 10px;">
                                <div style="width: 500px; height: 300px;">
                                    <a-spin :spinning="loadingAI">
                                        <img src="@/assets/authorInterest.png">
                                    </a-spin>
                                </div>
                            </div>
                        </div>
                        <div style="margin-top: 30px">
                            <span style="font-size: 20px; color: #0B0E47">
                                发表情况
                            </span>
                            <div style="margin-top: 10px; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.5); border-radius: 10px;">
                                <div ref="chart2" style="width: 500px; height: 300px;"></div>
                            </div>
                        </div>
                        <div style="margin-top: 30px">
                            <span style="font-size: 20px; color: #0B0E47">
                                被引情况
                            </span>
                            <div style="margin-top: 10px; box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.5); border-radius: 10px;">
                                <div ref="chart3" style="width: 500px; height: 300px;"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <a-modal v-model:visible="loginShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">欢迎登录</div>
                            <a-form
                                    :model="loginForm"
                                    name="normal_login"
                                    class="login-form"
                                    style="margin-top: 20px"
                                    @finish="onLoginFinish"
                            >
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请输入账号' }]"
                                >
                                    <a-input v-model:value="loginForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请输入密码' }]"
                                >
                                    <a-input-password v-model:value="loginForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-form-item name="remember" no-style>
                                        <a-checkbox v-model:checked="loginForm.remember">自动登录</a-checkbox>
                                    </a-form-item>
                                </a-form-item>

                                <a-form-item style="margin-top: -10px">
                                    <a-button :disabled="disabled" type="primary" html-type="submit" class="login-form-button" style="width: 100%">
                                        登录
                                    </a-button>
                                    <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 10px">
                                        <a href="">注册新用户</a>
                                        <a class="login-form-forgot" href="">忘记密码</a>
                                    </div>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
                <a-modal v-model:visible="registerShow" :footer="null" centered width="800px">
                    <div style="display: flex;">
                        <img src="@/assets/cut-theone-scholar-logo.png" style="width: 400px;">
                        <div>
                            <div style="color: #0B0E47; font-weight: 500; font-size: 30px">注册账号</div>
                            <a-form
                                    layout="horizontal"
                                    ref="formRef"
                                    :model="registerForm"
                                    style="margin-top: 20px"
                                    @finish="onRegisterFinish">
                                <a-form-item
                                        label="账号"
                                        name="username"
                                        :rules="[{ required: true, message: '请设置用户名' },{ message: '用户名已被占用', validator: validateUsername}]">
                                    <a-input v-model:value="registerForm.username">
                                        <template #prefix>
                                            <UserOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item
                                        label="密码"
                                        name="password"
                                        :rules="[{ required: true, message: '请设置密码' }]">
                                    <a-input-password v-model:value="registerForm.password">
                                        <template #prefix>
                                            <LockOutlined class="site-form-item-icon" />
                                        </template>
                                    </a-input-password>
                                </a-form-item>

                                <a-form-item
                                        label="身份"
                                        name="identity"
                                        :rules="[{ required: true, message: '请选择身份' }]">
                                    <a-select v-model:value="registerForm.identity" :options="identityOptions" placeholder="请选择身份"/>
                                </a-form-item>

                                <a-form-item
                                        label="邮箱"
                                        name="email">
                                    <a-input v-model:value="registerForm.email" placeholder="请绑定邮箱">
                                        <template #prefix>
                                            <mail-outlined class="site-form-item-icon" />
                                        </template>
                                    </a-input>
                                </a-form-item>

                                <a-form-item>
                                    <a-button :disabled="registerDisabled" type="primary" html-type="submit" style="width: 70%">
                                        注册
                                    </a-button>
                                    <a-button style="margin-left: 5%; width: 25%" @click="() => formRef.resetFields()">
                                        清空
                                    </a-button>
                                </a-form-item>
                            </a-form>
                        </div>
                    </div>
                </a-modal>
            </a-layout-content>
            <a-layout-footer style="background: #000; text-align: center">
                <p style="color:#fff">©{{ new Date().getFullYear() }} {{ systemTitle }}</p>
                <p style="color:#fff">
                    <a @click.prevent="$router.push('/about')">关于</a>&nbsp;|&nbsp;
                    <a>开发团队</a>&nbsp;|&nbsp;
                    <a href="https://gitee.com/shenyang-theone/theone-recsys">了解更多</a>
                </p>
            </a-layout-footer>
        </a-layout>
    </a-layout>
</template>

<script>
import {computed, defineComponent, onMounted, reactive, ref, toRefs} from "vue";
import {useRoute, useRouter} from "vue-router";
import {useStore} from "vuex";
import globalVariable from "@/components/mathJax/globalVariable";
import {logout as logout_request} from "@/api/post/logout";
import {login} from "@/api/post/login";
import {user_info} from "@/api/post/user_info";
import {notification} from "ant-design-vue";
import {register} from "@/api/post/register";
import {validate_username} from "@/api/post/validate_username";
import {
    DownOutlined, HeartFilled, HeartOutlined,
    UserOutlined
} from "@ant-design/icons-vue";
import {interest} from "@/api/post/interest";
import {author_publish} from "@/api/post/author_publish";
import {author_net} from "@/api/post/author_net";
import * as echarts from "echarts";
import {browsing} from "@/api/post/browsing";

export default defineComponent({
    components: {
        HeartFilled,
        HeartOutlined,
        UserOutlined,
        DownOutlined,
    },
    setup() {

        // -------------onMounted钩子，组件挂载完毕异步加载数据--------------
        onMounted(() => {
            // 取参数
            state.authorId = parseInt($route.query.author_id);
            state.login = !store.state.logout;
            state.searchField = $route.query.searchField || 'title';
            state.searchQuery = $route.query.searchQuery || '';
            state.tagsChecked = $route.query.tagsChecked ? JSON.parse($route.query.tagsChecked) : [];
            // 参数格式不正确
            if (isNaN(state.authorId)) {
                router.push('/homepage_demo')
            }

            const myChart2 = echarts.init(chart2.value);
            const myChart3 = echarts.init(chart3.value);

            author_publish(state.authorId).then((response) => {
                if(response.data.status.code===0){
                    state.loadingAI = false;

                    state.author = response.data.data.author;
                    state.paperList = response.data.data.paperList;
                    state.interest = response.data.data.interest;
                    document.title = state.author.author_name + "-作者详情";
                    // 处理数据：用于设置悬停样式，计算总被引量
                    let sum = 0;
                    state.paperList.forEach((paper) => {
                        sum += paper.citationCount;
                        // 区分Title，为每个paper设置单独的isTitleHovered属性
                        paper.isTitleHovered = false;
                        paper.authors.forEach((author) => {
                            // 区分author，为每个author设置单独的isHovered属性
                            author.isHovered = false;
                        });
                    });
                    state.citationCountSum = sum;

                    // 计算h指数
                    const citations = state.paperList.map(paper => paper.citationCount);
                    citations.sort((a, b) => b - a); // 按被引量从高到低排序
                    let hIndex = 0;
                    for (let i = 0; i < citations.length; i++) {
                        if (citations[i] >= i + 1) {
                            hIndex = i + 1;
                        } else {
                            break;
                        }
                    }
                    state.hIndex = hIndex; // 将计算得到的 h 指数存储到 Vuex 的状态中

                    // -------------构建发表情况折线图-------------
                    // 初始化统计结果对象
                    let yearPublicationCount = {};
                    // 遍历 paperList
                    state.paperList.forEach((paper) => {
                        // 解析论文的 update_date 字段
                        let updateDate = new Date(paper.update_date);
                        // 获取论文的年份
                        let paperYear = updateDate.getFullYear();
                        // 统计每年的发文量
                        if (!yearPublicationCount[paperYear]) {
                            yearPublicationCount[paperYear] = 1;
                        } else {
                            yearPublicationCount[paperYear]++;
                        }
                    });
                    // 获取年份数组和发文量数组
                    let yearArray = [];
                    let publicationArray = [];
                    Object.keys(yearPublicationCount).forEach((year) => {
                        yearArray.push(year.toString()); // 将年份转换为字符串
                        publicationArray.push(yearPublicationCount[year]);
                    });

                    const option2 = {
                        // title: {
                        //     top: '5%',
                        //     left: 'center',
                        //     text: '近 7 年发文量'
                        // },
                        tooltip: {
                            trigger: 'axis'
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {}
                            }
                        },
                        xAxis: {
                            type: 'category',
                            name: '年份',
                            boundaryGap: false,
                            data: yearArray
                        },
                        yAxis: {
                            type: 'value',
                            name: '发文量',
                        },
                        series: [
                            {
                                name: '发文量',
                                type: 'line',
                                data: publicationArray,
                            }
                        ]
                    };
                    myChart2.setOption(option2);

                    // -------------构建被引情况折线图-------------
                    // 初始化统计结果对象
                    let yearCitationCount = {};
                    // 遍历 paperList
                    state.paperList.forEach((paper) => {
                        // 解析论文的 update_date 字段
                        let updateDate = new Date(paper.update_date);
                        // 获取论文的年份
                        let paperYear = updateDate.getFullYear();
                        // 统计每年的被引量
                        if (!yearCitationCount[paperYear]) {
                            yearCitationCount[paperYear] = paper.citationCount;
                        } else {
                            yearCitationCount[paperYear] += paper.citationCount;
                        }
                    });
                    // 获取年份数组和被引量数组
                    let yearArray2 = [];
                    let citationCountArray = [];
                    Object.keys(yearCitationCount).forEach((year) => {
                        yearArray2.push(year.toString()); // 将年份转换为字符串
                        citationCountArray.push(yearCitationCount[year]);
                    });

                    const option3 = {
                        // title: {
                        //     top: '5%',
                        //     left: 'center',
                        //     text: '近 7 年发文量'
                        // },
                        tooltip: {
                            trigger: 'axis'
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {}
                            }
                        },
                        xAxis: {
                            type: 'category',
                            name: '年份',
                            data: yearArray2
                        },
                        yAxis: {
                            type: 'value',
                            name: '该年发文总被引量',
                        },
                        dataZoom: [
                            {
                                type: 'inside'
                            }
                        ],
                        series: [
                            {
                                name: '被引量',
                                type: 'bar',
                                data: citationCountArray,
                                showBackground: true,
                                backgroundStyle: {
                                    color: 'rgba(180, 180, 180, 0.2)'
                                }
                            }
                        ]
                    };
                    myChart3.setOption(option3);
                }
            })
            checkLaTex()

            // 构建作者合作网络关系图
            // 基于准备好的dom，初始化echarts实例
            const myChart = echarts.init(chart.value);
            // 显示加载中动画
            myChart.showLoading();
            // 异步加载数据
            author_net(state.authorId).then((response) => {
                if(response.data.status.code===0){
                    console.log("获取作者合作网络成功")

                    // 隐藏加载中动画
                    myChart.hideLoading();

                    const papers = response.data.data.paperList;
                    // 绑定数据
                    // state.paperList = papers;

                    // 将获取到的author_net数据转化为graph关系
                    for (let i = 0; i < papers.length; i++) {
                        // 声明当前遍历的论文
                        let paper = papers[i];
                        // 添加类别
                        let newCategory = {
                            "name": "文章"+(i+1)
                        }
                        graph.categories.push(newCategory);
                        // 获取该论文的所有作者
                        let authors = paper.authors;
                        for (let j = 0; j < authors.length; j++) {
                            // 声明当前遍历的作者
                            let author = authors[j];
                            // 添加前进行判断，以免节点重复
                            let isNodeExist = graph.nodes.some(node => node.id === author.author_id.toString());
                            if (!isNodeExist){
                                // 添加新节点
                                let newNode = {
                                    // id必须是string类型!!!
                                    "id": author.author_id.toString(),
                                    "name": author.author_name,
                                    // 发文量
                                    "output": 0,
                                    // 节点大小，跟发文量有关
                                    "symbolSize": 20,
                                    "category": i
                                };
                                graph.nodes.push(newNode);
                            }
                            // 添加边，排列组合
                            for (let k = j+1; k < authors.length; k++) {
                                // 声明当前遍历的作者
                                let author_next = authors[k];
                                // 添加前计算重复次数（即已记录的二人合作的论文数），如果存在，设置其他曲率值，通过两节点间存在多条边模拟合著多篇论文
                                let duplicateCount = graph.links.filter(link =>
                                        (link.source === author.author_id.toString() && link.target === author_next.author_id.toString()) ||
                                        (link.source === author_next.author_id.toString() && link.target === author.author_id.toString())
                                ).length;
                                let newLink = {
                                    "source": author.author_id.toString(),
                                    "target": author_next.author_id.toString(),
                                    "title": paper.title,
                                    "paper_id": paper.paper_id,
                                    "update_date": paper.update_date,
                                    lineStyle: {
                                        curveness: 0.3+duplicateCount*0.1
                                    },
                                };
                                graph.links.push(newLink);
                            }
                        }
                    }

                    // 根据每个节点的关联边数重新设置节点的symbolSize值
                    // 统计每个节点的关联边数
                    let nodeEdgeCounts = {};
                    for (let i = 0; i < graph.links.length; i++) {
                        let link = graph.links[i];
                        nodeEdgeCounts[link.source] = (nodeEdgeCounts[link.source] || 0) + 1;
                        nodeEdgeCounts[link.target] = (nodeEdgeCounts[link.target] || 0) + 1;
                    }
                    // 设置节点的output与symbolSize
                    graph.nodes.forEach(node => {
                        let edgeCount = nodeEdgeCounts[node.id] || 0;
                        // 设置节点的 output 值
                        node.output = edgeCount;
                        // 计算新的 symbolSize 值
                        let newSize = 20 + Math.floor(edgeCount / 10) * 10;
                        // 设置节点的 symbolSize 值
                        node.symbolSize = newSize;
                    });

                    // 根据symbolSize判断是否显示label
                    graph.nodes.forEach(function (node) {
                        node.label = {
                            show: node.symbolSize > 20
                        };
                    });

                    // 指定图表的配置项和数据
                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: function(params) {
                                if (params.dataType === 'edge') { // 如果当前是边
                                    return '<论文信息><br/>题名:&emsp;&emsp;&nbsp;'+params.data.title+'<br/>论文id:&emsp;&nbsp;'+params.data.paper_id+'<br/>发表日期:&nbsp;'+params.data.update_date; // 返回边的 link.label 字段作为提示框内容
                                } else { // 如果是节点
                                    return '<作者信息><br/>姓名:&emsp;&emsp;&nbsp;'+params.data.name+'<br/>作者id:&emsp;&nbsp;'+params.data.id+'<br/>总发文量:&nbsp;'+params.data.output; // 默认显示系列名和节点名
                                }
                            }
                        },
                        // legend: [
                        //     {
                        //         data: graph.categories.map(function (a) {
                        //             return a.name;
                        //         })
                        //     }
                        // ],
                        animationDuration: 1500,
                        animationEasingUpdate: 'quinticInOut',
                        series: [
                            {
                                name: 'Author_Net',
                                type: 'graph',
                                // edgeLabel: {
                                //     show: true, // 设置为 true 显示边的标签
                                //     formatter: function(params) {
                                //         return params.data.label; // 假设数据中包含 weight 属性，表示权重
                                //     }
                                // },
                                layout: 'circular',
                                // circular: {
                                //     rotateLabel: true // 旋转标签
                                // },
                                data: graph.nodes,
                                links: graph.links,
                                categories: graph.categories,
                                // 开启平移和缩放
                                roam: true,
                                label: {
                                    position: 'right',
                                    formatter: '{b}'
                                },
                                // 自动隐藏重叠标签
                                labelLayout: {
                                    hideOverlap: true
                                },
                                // scaleLimit: {
                                //     min: 0.4,
                                //     max: 2
                                // },
                                lineStyle: {
                                    color: 'source',
                                    // curveness: 0.3
                                },
                                emphasis: {
                                    // 强调节点
                                    focus: 'adjacency',
                                    // 突出显示边
                                    lineStyle: {
                                        width: 10
                                    }
                                }
                            }
                        ]
                    };

                    // 使用刚指定的配置项和数据显示图表。
                    myChart.setOption(option);

                    // 添加点击事件监听器
                    myChart.on('click', function(params) {
                        if (params.dataType === 'node') {
                            // 如果点击的是节点，跳转至该作者信息界面
                            let author_id = params.data.id;
                            window.open('/author_show_demo?author_id=' + author_id, '_blank')
                        }
                        else {
                            // 如果点击的是边，跳转至该论文信息界面
                            let paper_id = params.data.paper_id;
                            window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
                        }
                    });
                }
            })
        });

        // ----------------定义的function，由下至上编写---------------

        const handleInterest = (author_id) => {
            // 点击关注/取消：数据存入数据库中，但是前端直接修改收藏状态，无需重新获取数据
            interest(author_id).then((response) => {
                if(response.data.status.code===0){
                    state.interest = !state.interest;
                }
            });
        }

        const handleAuthor = (author_id) => {
            window.open('/author_show_demo?author_id=' + author_id, '_blank')
        }

        const handleRead = (paper_id) => {
            // 记录用户浏览论文历史
            browsing(paper_id).then((response) => {
                if(response.data.status.code === 0){
                    console.log("浏览埋点设置成功")
                }
            })
            window.open('/paper_show_demo?paper_id=' + paper_id, '_blank')
        }

        const onSearch = () => {
            router.push('/ordinarySearch_demo?searchField='+state.searchField+'&searchQuery='+state.searchQuery+'&tagsChecked='+JSON.stringify(state.tagsChecked.slice()))
        }

        const registerDisabled = computed(() => {
            return !(registerForm.username && registerForm.password && registerForm.identity);
        });

        const validateUsername = (rule, value) => {
            return new Promise((resolve, reject) => {
                if (value.length === 0) {
                    resolve()
                }
                validate_username(value).then((response) => {
                    const { code, message } = response.data.status
                    if (code === 0) {
                        resolve()
                    } else {
                        reject(message)
                    }
                })
            })
        }

        const onRegisterFinish = values => {
            register(values.email, values.username, values.password, values.identity).then((response) => {
                if (response.data.status.code === 0) {
                    //注册成功
                    store.commit('CLEAR_USER_INFO')
                    store.commit('SET_TOKEN', response.data.data)
                    notification['success']({
                        message: '成功',
                        description: '注册成功',
                    })
                    state.loginShow = true;
                    state.registerShow = false;
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })
        }

        const onRegisterShow = () => {
            state.loginShow = false;
            state.registerShow = true;
        };

        const onLoginFinish = values => {
            login(values.username, values.password, values.remember).then((response) => {
                store.commit('CLEAR_USER_INFO')
                store.commit('CLEAR_TOKEN')
                if (response.data.status.code === 0) {
                    state.loginShow = false;
                    state.login = true;

                    store.commit('SET_LOGOUT', false)
                    //成功后继续请求用户信息
                    store.commit('SET_TOKEN', response.data.data)
                    console.log(response.data.data)
                    user_info()
                            .then((response) => {
                                if (response.data.status.code === 0) {
                                    // 成功后设置用户信息
                                    store.commit('SET_USER_INFO', response.data.data.user)
                                    console.log(response.data.data.user)
                                    // if ($route.redirectedFrom) {
                                    //     router.push({
                                    //         path: decodeURIComponent($route.redirectedFrom.fullPath),
                                    //     })
                                    // } else {
                                    //     router.push('/')
                                    // }
                                } else {
                                    notification['error']({
                                        message: '错误',
                                        description: response.data.status.message,
                                    })
                                }
                            })
                            .catch()
                } else if (response.data.status.code === 1 || response.data.status.code === 2) {
                    notification['warning']({
                        message: '登录失败',
                        description: '您提供的用户名或密码无效',
                    })
                } else {
                    notification['error']({
                        message: '错误',
                        description: response.data.status.message,
                    })
                }
            })

        };

        const onLoginShow = () => {
            state.loginShow = true;
        };

        const logout = () => {
            state.login = false;
            logout_request()
                    .then((response) => {
                        if (response.data) {
                            //退出成功
                            store.commit('SET_LOGOUT', true)
                            store.commit('CLEAR_USER_INFO')
                            store.commit('CLEAR_TOKEN')
                            // 清空本地存储的数据
                            sessionStorage.clear()
                            // 其他操作...
                        }
                    })
                    .catch(() => {
                        store.commit('SET_LOGOUT', true)
                        store.commit('CLEAR_USER_INFO')
                        store.commit('CLEAR_TOKEN')
                    })
        }

        const onMenuClick = ({ key }) => {
            switch (key) {
                case 'center': {
                    window.open('/user_center_demo', '_blank')
                    break
                }
                case 'favorite': {
                    window.open('/user_center_demo?currentKey=3&&selectedKeys=3&&openKeys=2', '_blank')
                    break
                }
                case 'interest': {
                    window.open('/user_center_demo?currentKey=4&&selectedKeys=4&&openKeys=2', '_blank')
                    break
                }
                case 'logout': {
                    logout()
                }
            }
        }

        const checkLaTex = () => {
            globalVariable.initMathjaxConfig();
            globalVariable.MathQueue();
        }

        // --------------------定义的vue变量------------------------
        // 确保在使用 '$route' 之前已经声明并初始化了它
        const router = useRouter()
        const $route = useRoute();
        const store = useStore()

        // --------------------定义的响应数据-----------------------
        const chart = ref();
        const chart2 = ref();
        const chart3 = ref();

        const state = reactive({
            hIndex: 0,
            loadingAI: true,
            citationCountSum: 0,
            author: null,
            paperList: [],
            interest: false,
            authorId: -1,
            formRef: null,
            registerShow: false,
            loginShow: false,
            login: true,
            searchOptions: [
                { label: '标题', value: 'title' },
                { label: '摘要', value: 'abstract' },
                { label: '作者', value: 'author' },
                { label: '期刊', value: 'journal' },
            ],
            searchQuery: '',
            searchField: 'title',
            backGroundImg: require('@/assets/background2.png'),
            systemTitle: process.env.VUE_APP_TITLE,
        })

        const registerForm = reactive({
            username: '',
            password: '',
            identity: null,
            email: '',
        });

        const loginForm = reactive({
            username: '',
            password: '',
            remember: false,
        });

        // ----------------------定义的常量--------------------
        const graph = {
            "nodes": [],
            "links": [],
            "categories": []
        }

        const identityOptions = [{
            label: '学生',
            value: '1',
        }, {
            label: '教授',
            value: '2',
        }, {
            label: '副教授',
            value: '3',
        }, {
            label: '讲师',
            value: '4',
        }]

        // ----------------------return函数-------------------
        return {
            chart3,
            chart2,
            chart,
            handleInterest,
            handleAuthor,
            handleRead,
            onSearch,
            registerDisabled,
            validateUsername,
            identityOptions,
            onRegisterFinish,
            onRegisterShow,
            onLoginFinish,
            onLoginShow,
            onMenuClick,
            ...toRefs(state),
            registerForm,
            loginForm,
        }

    },
})
</script>

<style scoped>
.active {
    background-color: #4F4F4F;
    color: white;
}
.inactive {
    background-color: white;
    color: #4F4F4F;
}

/*分割线*/
.custom-divider {
    border: none;
    height: 1px;
    background-color: #BBBBBB;
}
</style>